package org.example.rzfx.controller;

import org.example.rzfx.annotation.OperationLog;
import org.example.rzfx.dto.LogExportDTO;
import org.example.rzfx.dto.LogQueryDTO;
import org.example.rzfx.dto.LogStatDTO;
import org.example.rzfx.dto.PageResult;
import org.example.rzfx.dto.Result;
import org.example.rzfx.entity.Log;
import org.example.rzfx.service.LogExportService;
import org.example.rzfx.service.LogService;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

/**
 * 日志控制器
 */
@RestController
@RequestMapping("/api/log")
@CrossOrigin
public class LogController {
    
    @Resource
    private LogService logService;
    
    @Resource
    private LogExportService logExportService;
    
    /**
     * 查询日志
     */
    @PostMapping("/query")
    public Result<PageResult<Log>> queryLogs(@RequestBody LogQueryDTO queryDTO) {
        try {
            PageResult<Log> result = logService.queryLogs(queryDTO);
            return Result.success(result);
        } catch (Exception e) {
            return Result.error(e.getMessage());
        }
    }
    
    /**
     * 获取日志详情
     */
    @GetMapping("/{id}")
    public Result<Log> getLogDetail(@PathVariable Long id) {
        Log log = logService.getById(id);
        if (log == null) {
            return Result.error("日志不存在");
        }
        return Result.success(log);
    }
    
    /**
     * 统计日志
     */
    @GetMapping("/stat")
    public Result<LogStatDTO> statLogs(
            @RequestParam @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") LocalDateTime startTime,
            @RequestParam @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") LocalDateTime endTime) {
        try {
            LogStatDTO statDTO = logService.statLogs(startTime, endTime);
            return Result.success(statDTO);
        } catch (Exception e) {
            return Result.error(e.getMessage());
        }
    }
    
    /**
     * 删除日志
     */
    @DeleteMapping("/{id}")
    @OperationLog(type = "DELETE", description = "删除日志")
    public Result<Void> deleteLog(@PathVariable Long id) {
        logService.removeById(id);
        return Result.success("删除成功", null);
    }
    
    /**
     * 导出日志
     */
    @PostMapping("/export")
    @OperationLog(type = "EXPORT", description = "导出日志数据")
    public ResponseEntity<byte[]> exportLogs(@RequestBody LogExportDTO exportDTO) {
        try {
            byte[] data = logExportService.exportToCsv(exportDTO);
            
            String fileName = "logs_" + LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyyMMdd_HHmmss")) + ".csv";
            
            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
            headers.setContentDispositionFormData("attachment", fileName);
            headers.setContentLength(data.length);
            
            return ResponseEntity.ok()
                .headers(headers)
                .body(data);
        } catch (Exception e) {
            return ResponseEntity.internalServerError().build();
        }
    }
}

